package org.code.mallspringboot.config;

import org.code.mallspringboot.filter.JwtAuthenticationTokenFilter;
import org.code.mallspringboot.service.impl.UmsAdminServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * spring security 配置
 * @author jamie
 */
@Configuration
@EnableMethodSecurity
public class SecurityConfig {

    @Autowired
    UmsAdminServiceImpl umsAdminService;

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().requestMatchers("/admin/login");
    }

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {

        //放开登录权限
        httpSecurity.authorizeHttpRequests(a->a
                .requestMatchers("/mall-admin/admin/login").permitAll()
                .anyRequest().authenticated());

        //cors
//        httpSecurity.cors(AbstractHttpConfigurer::disable);
        //csrf
        httpSecurity.csrf(AbstractHttpConfigurer::disable);
        //基于token,禁止Session
        httpSecurity.sessionManagement(session->session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        //userService
        httpSecurity.userDetailsService(umsAdminService);
        //过滤器
        httpSecurity.addFilterBefore(new JwtAuthenticationTokenFilter(umsAdminService), UsernamePasswordAuthenticationFilter.class);

        return httpSecurity.build();
    }

}
